package com.ujiuye.demo;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class SolrTest {

    public static void main(String[] args) throws Exception {
        queryHight();
    }


    /**
     * 增加文档
     *
     * @throws Exception
     */
    public static void create() throws Exception {
        String URL = "http://192.168.21.129:8983/solr/collection1";
        HttpSolrClient client = new HttpSolrClient
                .Builder(URL)
                .withConnectionTimeout(1000)
                .withSocketTimeout(6000)
                .build();
        // 创建数据
        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id", "5678");
        doc.addField("product_catalog_name", "智能数码");
        doc.addField("product_price", "4688.00");
        doc.addField("product_name", "佳能750D单反相机");
        client.add(doc);
        client.commit();
    }

    /**
     * 检索文档
     *
     * @throws Exception
     */
    @Test
    public static void query() throws Exception {
        String URL = "http://192.168.21.129:8983/solr/collection1";
        HttpSolrClient client = new HttpSolrClient.Builder(URL)
                .withConnectionTimeout(1000)
                .withSocketTimeout(6000)
                .build();
        // 定义查询内容（q关键字，列名:查询关键字）
        SolrQuery query = new SolrQuery("product_name:佳能750D单反相机");

        //query.addFilterQuery("product_catalog_name:" + "幽默杂货");
        // 按照商品价格范围进行过滤（0-100）
        //query.addFilterQuery("product_price:[0 TO 100000]");

        // 对检索结果按照价格从低到高进行排序
        //query.setSort("product_price",ORDER.asc);

        QueryResponse rsp = client.query(query);
        SolrDocumentList results = rsp.getResults();
        System.out.println(results.getNumFound());// 查询总条数
        for (SolrDocument doc : results) {
            System.out.println(doc);
        }
    }

    /**
     * 删除文档
     *
     * @throws Exception
     */
    public static void Del() throws Exception {

        String URL = "http://192.168.21.129:8983/solr/collection1";
        HttpSolrClient client = new HttpSolrClient
                .Builder(URL)
                .withConnectionTimeout(1000)
                .withSocketTimeout(6000)
                .build();

        // 删除所有分词
        // client.deleteByQuery("*:*");

        // 根据id删除所有分词
        client.deleteById("5678");
        client.commit();
    }


    /**
     * 关键词高亮显示
     * @throws Exception
     */
    public static void queryHight() throws Exception {
        String URL = "http://192.168.21.129:8983/solr/collection1";
        HttpSolrClient client = new HttpSolrClient
                .Builder(URL)
                .withConnectionTimeout(1000)
                .withSocketTimeout(6000)
                .build();

        // 定义查询内容 * 代表查询所有 这个是基于结果集
        SolrQuery query = new SolrQuery(); // 定义查询内容
        query.setQuery("小夜灯");// query.setQuery("product_name:小夜灯");
        // 设置默认搜索域（注意：如果需要高亮，必须设定默认搜索字段或者设定指定字段）
        query.set("df","product_name");

        query.setHighlight(true);
        query.addHighlightField("product_name");// 设置高亮字段
        query.setHighlightSimplePre("<em style='color:red'>");//设置高亮前缀
        query.setHighlightSimplePost("</em>");// 设置高亮后缀

        query.setStart(0);// 起始页
        query.setRows(3);// 每页显示数量

        QueryResponse rsp = client.query(query);

        //第一个Map的键是文档的ID，第二个Map的键是高亮显示的字段名
        Map<String,Map<String,List<String>>> highlighting = rsp.getHighlighting();

        SolrDocumentList results = rsp.getResults();
        System.out.println(results.getNumFound());// 查询总条数
        for (SolrDocument doc : results) {
            // doc.get("id") 获取到ID的数值
            List<String> list2=highlighting.get(doc.get("id")).get("product_name");

            System.out.println("id:" + doc.getFieldValue("id"));
            System.out.println("product_name:"+doc.getFieldValue("product_name"));
            if (list2 != null && list2.size() > 0) {
                System.out.println("product_name hight:"+list2.get(0));
            }
            System.out.println(doc);
        }
    }

}
